//
//  MasterViewController.m
//  SQLite3Master-DetailAPP
//
//  Created by ficow on 7/7/16.
//  Copyright © 2016年 ficow. All rights reserved.
//

#import "MasterViewController.h"
#import "DetailViewController.h"
#import "DBAccess.h"
#import "Product.h"
#import "CatalogTableViewCell.h"

static NSString *reuseIdentifier = @"Cell";

@interface MasterViewController ()<UISearchResultsUpdating>

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) NSMutableArray *searchResults;

@end

@implementation MasterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
    
    self.title = NSLocalizedString(@"Catalog", @"Catalog");
    //[self.tableView registerClass:NSClassFromString(@"CatalogTableViewCell") forCellReuseIdentifier:@"Cell"];
    //[self initializeProductsData];
    [self configIndexCollation];
    [self configSearchController];
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.clearsSelectionOnViewWillAppear = self.splitViewController.isCollapsed;
    [super viewWillAppear:animated];
}

- (void)initializeProductsData{
    
    DBAccess *dba = [[DBAccess alloc]init];
    self.products = [dba getAllProducts];
    [dba closeDatabase];
}

- (void)configIndexCollation{
    DBAccess *dba = [[DBAccess alloc]init];
    NSMutableArray *productsTemp = [dba getAllProducts];
    [dba closeDatabase];
    
    UILocalizedIndexedCollation *ic = [UILocalizedIndexedCollation currentCollation];
    for(Product *pd in productsTemp){
        NSInteger section = [ic sectionForObject:pd collationStringSelector:@selector(name)];
        pd.section = section;
    }
    NSInteger sectionCount = [[ic sectionTitles]count];
    NSMutableArray *sectionsArray = [NSMutableArray arrayWithCapacity:sectionCount];
    for (int i = 0 ; i <= sectionCount; i++) {
        NSMutableArray *singleSectionArray = [NSMutableArray arrayWithCapacity:1];
        [sectionsArray addObject:singleSectionArray];
    }
    for (Product *theProduct in productsTemp) {
        [(NSMutableArray*)[sectionsArray objectAtIndex:theProduct.section] addObject:theProduct];
    }
    self.products = [NSMutableArray new];
    for (NSMutableArray *singleSectionArray in sectionsArray) {
        NSArray *sortedSection = [ic sortedArrayFromArray:singleSectionArray collationStringSelector:@selector(name)];
        [self.products addObject:sortedSection];
    }
}

- (void)configSearchController{
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.searchController.searchBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
    self.searchController.dimsBackgroundDuringPresentation = false;
    self.tableView.tableHeaderView = self.searchController.searchBar;
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.backgroundColor = [UIColor greenColor];
    self.searchController.searchResultsUpdater = self;
}

- (NSMutableArray*)searchResults{
    if (_searchResults != nil) {
        return _searchResults;
    }
    _searchResults = [NSMutableArray new];
    return _searchResults;
}

#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        Product *product = self.products[indexPath.row];
        DetailViewController *controller = (DetailViewController *)[[segue destinationViewController] topViewController];
        [controller setDetailItem:product.name];
        controller.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem;
        controller.navigationItem.leftItemsSupplementBackButton = YES;
    }
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.searchController.active){
        return 1;
    }
    return [self.products count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.searchController.active){
        return [self.searchResults count];
    }
    return [[self.products objectAtIndex:section]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    if (self.searchController.active) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }
        cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
        return cell;
    }
    
    cell = (CatalogTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[CatalogTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    Product *product = [[self.products objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]]; // for index
    cell.textLabel.text = product.name;
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.products removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

//for index
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if ([[self.products objectAtIndex:section] count] > 0) {
        return [[[UILocalizedIndexedCollation currentCollation]sectionTitles]objectAtIndex:section];
    }
    return nil;
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView{
    return [[UILocalizedIndexedCollation currentCollation]sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return [[UILocalizedIndexedCollation currentCollation]sectionForSectionIndexTitleAtIndex:index];
}

//for searchController
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    [self.searchResults removeAllObjects];
    //NSPredicate用法参考 http://blog.csdn.net/likendsl/article/details/7570181
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] $SEARCHTEXT"];
    NSDictionary *dict = @{@"SEARCHTEXT":self.searchController.searchBar.text};
    NSPredicate *searchPredicate = [predicate predicateWithSubstitutionVariables:dict];
    for (NSArray *sectionArray in self.products) {
        for (Product *product in sectionArray) {
            NSLog(@"checking : %@",product.name);
            if ([searchPredicate evaluateWithObject:product]) {
                [self.searchResults addObject:product.name];
            }
        }
    }
    [self.tableView reloadData];
}

@end
